<?php

namespace app\admin\service;

use app\model\platform\PlatformTaskModel;
use app\model\RatingScaleModel;
use app\model\TaskModel;
use app\model\TaskUserModel;
use app\model\WorkersTaskModel;
use app\model\WorkersTaskUserModel;
use think\Service;

class GroupReportExportService extends Service
{
    /**
     * 任务测评团体报告导出数据（优化版）
     * @param $task_id
     * @param $rating_scale_id
     * @param $uid
     * @return bool|string
     */
    public function TaskGroupReportExportData($task_id, $rating_scale_id, $uid): bool|string
    {
        try {
            $TaskUserModel = new TaskUserModel();
            // 1. 查询优化：只获取需要的字段，减少数据传输量
            $query = $TaskUserModel->field('id,uid,result_id,is_finish')->where([
                    ['task_id', '=', $task_id],
                    ['rating_scale_id', '=', $rating_scale_id],
                    ['uid', 'in', $uid]
                ])
                ->with([
                    'user',
                    'TaskUserResult' => function ($query) {
                        $query->with([
                            'TaskFactorScore' => function ($query) {
                                // 只加载因子统计必要字段
                                $query->with([
                                        'TeamRatingScaleFactor',
                                        'RatingScaleFactorWarning'
                                    ]);
                            }
                        ]);
                    }
                ]);

            // 2. 大数据量分批处理（每次100条），避免内存溢出
            $batchSize = 200;
            $target_num = 0; // 先统计总数，避免全量加载后count
            $involved_num = 0;
            $involved_boy_num = 0;
            $involved_girl_num = 0;
            $not_involved_num = 0;
            $not_involved_boy_num = 0;
            $not_involved_girl_num = 0;
            $normal_report_num = 0;
            $invalid_report_num = 0;
            $warning_report_num = 0;
            $warning_report_boy_num = 0;
            $warning_report_girl_num = 0;
            $warning_report_level = [];

            // 实时统计总分相关（避免array_column+array_filter的二次遍历）
            $totalScoreSum = 0;
            $totalScoreCount = 0;
            $lowest_overall_score = null;
            $highest_overall_score = null;

            // 因子信息实时统计（避免先存数组再处理）
            $FactorInfo = [];
            $FactorWarningArray = [];
            $WarningReportNum = 0;
            $overall_report_score_sum = 0;
            $lowest_report_score = null;
            $highest_report_score = null;

            // 预警因子统计
            $WarningFactorStats = [
                'count' => 0,
                'sum' => 0,
                'min' => null,
                'max' => null
            ];

            $user_answer_num = 0;

            // 分批处理数据
            $query->cache(true,300)->chunk($batchSize, function ($chunk) use (
                &$target_num,
                &$involved_num, &$involved_boy_num, &$involved_girl_num,
                &$not_involved_num, &$not_involved_boy_num, &$not_involved_girl_num,
                &$normal_report_num, &$invalid_report_num, &$warning_report_num,
                &$warning_report_boy_num, &$warning_report_girl_num, &$warning_report_level,
                &$totalScoreSum, &$totalScoreCount, &$lowest_overall_score, &$highest_overall_score,
                &$FactorInfo, &$FactorWarningArray, &$WarningReportNum, &$overall_report_score_sum,
                &$lowest_report_score, &$highest_report_score, &$WarningFactorStats, &$user_answer_num
            ) {
                $chunkData = $chunk->toArray();
                foreach ($chunkData as $item) {
                    $target_num++;
                    // 统计用户测评次数
                    if ($item['answer_role'] == 1) {
                        $user_answer_num++;
                    }

                    // 处理总分统计（实时计算，避免后续array_column）
                    if (!empty($item['total_score'])) {
                        $totalScoreSum += $item['total_score'];
                        $totalScoreCount++;
                        $lowest_overall_score = is_null($lowest_overall_score)
                            ? $item['total_score']
                            : min($lowest_overall_score, $item['total_score']);
                        $highest_overall_score = is_null($highest_overall_score)
                            ? $item['total_score']
                            : max($highest_overall_score, $item['total_score']);
                    }

                    if ($item['is_finish'] == 1) {
                        $currentWarningFactorNum = 0; // 当前用户的预警因子数

                        // 参与人性别统计
                        if ($item['sex'] == 1) {
                            $involved_boy_num++;
                        } elseif ($item['sex'] == 2) {
                            $involved_girl_num++;
                        }
                        $involved_num++;

                        // 报告有效性统计
                        if ($item['is_valid'] == 0) {
                            $invalid_report_num++;
                            continue;
                        } elseif ($item['is_warning'] == 1) {
                            $warning_report_num++;
                            // 性别统计
                            if ($item['sex'] == 1) {
                                $warning_report_boy_num++;
                            } elseif ($item['sex'] == 2) {
                                $warning_report_girl_num++;
                            }
                        } else {
                            $normal_report_num++;
                        }



                        // 因子处理
                        foreach ($item['TaskFactorScore']??[] as $factor) {
                            $factorName = $factor['factor_name'];
                            $factorId = $factor['factor_id'];

                            // 初始化因子统计结构
                            if (!isset($FactorInfo[$factorName])) {
                                $FactorInfo[$factorName] = [
                                    'name' => $factorName,
                                    'min' => $factor['score'],
                                    'max' => $factor['score'],
                                    'sum' => $factor['score'],
                                    'count' => 1,
                                    'factor_explain' => $factor['factor_explain'] ?? '',
                                    'warning_arr' => [],
                                    'normal' => 1
                                ];
                            } else {
                                // 实时更新因子的min/max/sum/count
                                $FactorInfo[$factorName]['min'] = min($FactorInfo[$factorName]['min'], $factor['score']);
                                $FactorInfo[$factorName]['max'] = max($FactorInfo[$factorName]['max'], $factor['score']);
                                $FactorInfo[$factorName]['sum'] += $factor['score'];
                                $FactorInfo[$factorName]['count']++;
                                $FactorInfo[$factorName]['normal']++;
                            }

                            // 预警因子处理
                            if ($factor['is_warning'] == 1) {
                                $currentWarningFactorNum++;
                                $WarningReportNum++;
                                $overall_report_score_sum += $factor['score'];

                                // 预警因子分数统计
                                $lowest_report_score = is_null($lowest_report_score)
                                    ? $factor['score']
                                    : min($lowest_report_score, $factor['score']);
                                $highest_report_score = is_null($highest_report_score)
                                    ? $factor['score']
                                    : max($highest_report_score, $factor['score']);

                                // 因子预警次数统计
                                if (!isset($FactorWarningArray[$factorId])) {
                                    $FactorWarningArray[$factorId] = [
                                        'factor_name' => $factorName,
                                        'num' => 1
                                    ];
                                } else {
                                    $FactorWarningArray[$factorId]['num']++;
                                }

                                // 因子预警详情统计
                                if (!isset($FactorInfo[$factorName]['warning_arr'][$factor['warning_mark_count']])) {
                                    $FactorInfo[$factorName]['warning_arr'][$factor['warning_mark_count']] = 1;
                                } else {
                                    $FactorInfo[$factorName]['warning_arr'][$factor['warning_mark_count']]++;
                                }
                                $FactorInfo[$factorName]['normal']--; // 正常数减去预警数

                                // 预警分级统计
                                if (!isset($warning_report_level[$factorId])) {
                                    $warning_report_level[$factorId] = [
                                        'name' => $factorName,
                                        'num' => 1,
                                        'boy' => $item['sex'] == 1 ? 1 : 0,
                                        'girl' => $item['sex'] == 2 ? 1 : 0
                                    ];
                                } else {
                                    $warning_report_level[$factorId]['num']++;
                                    if ($item['sex'] == 1) {
                                        $warning_report_level[$factorId]['boy']++;
                                    } elseif ($item['sex'] == 2) {
                                        $warning_report_level[$factorId]['girl']++;
                                    }
                                }
                            }
                        }

                        // 预警因子数量统计（当前用户）
                        if ($currentWarningFactorNum > 0) {
                            $WarningFactorStats['count']++;
                            $WarningFactorStats['sum'] += $currentWarningFactorNum;
                            $WarningFactorStats['min'] = is_null($WarningFactorStats['min'])
                                ? $currentWarningFactorNum
                                : min($WarningFactorStats['min'], $currentWarningFactorNum);
                            $WarningFactorStats['max'] = is_null($WarningFactorStats['max'])
                                ? $currentWarningFactorNum
                                : max($WarningFactorStats['max'], $currentWarningFactorNum);
                        }
                    } else {
                        // 未参与统计
                        if ($item['sex'] == 1) {
                            $not_involved_boy_num++;
                        } elseif ($item['sex'] == 2) {
                            $not_involved_girl_num++;
                        }
                        $not_involved_num++;
                    }
                }
                // 释放当前批次数据内存
                unset($chunkData);
            });

            // 计算总分统计值
            $lowest_overall_score = $lowest_overall_score ?? 0;
            $highest_overall_score = $highest_overall_score ?? 0;
            $overall_average_score = $totalScoreCount > 0
                ? round($totalScoreSum / $totalScoreCount, 2)
                : 0;

            // 计算预警报告平均分
            $overall_report_score = $WarningReportNum > 0
                ? round($overall_report_score_sum / $WarningReportNum, 2)
                : 0;
            $lowest_report_score = $lowest_report_score ?? 0;
            $highest_report_score = $highest_report_score ?? 0;

            // 计算预警因子统计值
            $lowest_warning_factor = $WarningFactorStats['count'] > 0
                ? $WarningFactorStats['min']
                : 0;
            $highest_warning_factor = $WarningFactorStats['count'] > 0
                ? $WarningFactorStats['max']
                : 0;
            $overall_warning_factor = $WarningFactorStats['count'] > 0
                ? round($WarningFactorStats['sum'] / $WarningFactorStats['count'], 2)
                : 0;

            // 格式化因子信息（计算平均分）
            $FactorInfo = array_map(function ($item) use ($target_num,$invalid_report_num) {
                $item['sum'] += $invalid_report_num;
                $item['average'] = round($item['sum'] / $item['count'], 2);

                // 转换预警详情为数组并按name排序
                $warningArr = [];
                foreach ($item['warning_arr'] as $name => $num) {
                    $warningArr[] = [
                        'id' => $name,
                        'name' => match ($name){
                            1 => '一级预警',
                            2 => '二级预警',
                            3 => '三级级预警',
                            4 => '四级级预警',
                            5 => '五级级预警',
                            default => '无效报告',
                        },
                        'num' => $num
                    ];
                }
                // 按name字段从小到大排序（字符串比较）
                usort($warningArr, function ($a, $b) {
                    return strcmp($a['id'], $b['id']);
                });
                $warningArr[] = ['name' => '无效报告','num' => $invalid_report_num];
                $item['warning_arr'] = $warningArr;

                unset($item['sum'], $item['count']); // 移除临时计算字段
                return $item;
            }, $FactorInfo);
            $FactorInfo = array_values($FactorInfo);

            // 处理预警因子排序
            $WarningFactorArrayList = [];
            foreach ($FactorWarningArray as $item) {
                $WarningFactorArrayList[] = $item;
            }
            array_multisort(array_column($WarningFactorArrayList, 'num'), SORT_DESC, $WarningFactorArrayList);

            // 生成预警因子名称字符串
            $WarningFactorArrayName = implode('、', array_column($FactorWarningArray, 'factor_name'));
            $WarningFactorArrayName2 = implode('、', array_column($WarningFactorArrayList, 'factor_name'));

            // 格式化预警分级统计
            $warning_report_level2 = array_values(array_map(function ($item) {
                return [
                    'name' => $item['name'],
                    'num' => $item['num'],
                    'boy' => $item['boy'] ?? 0,
                    'girl' => $item['girl'] ?? 0
                ];
            }, $warning_report_level));

            // 获取量表和任务信息（保持原实例化方式）
            $RatingScaleModel = new RatingScaleModel();
            $RatingScaleInfo = $RatingScaleModel->with('RatingScaleMode')->find($rating_scale_id);
            $TaskModel = new TaskModel();
            $TaskInfo = $TaskModel->with(['user' => function ($query) {
                $query->with(['unitName']);
            }])->find($task_id);

            return success([
                'WarningFactorArrayName2' => $WarningFactorArrayName2,
                'WarningFactorArrayName' => $WarningFactorArrayName,
                'WarningFactorArrayList' => $WarningFactorArrayList,
                'target_num' => $target_num,
                'involved_num' => $involved_num,
                'involved_boy_num' => $involved_boy_num,
                'involved_girl_num' => $involved_girl_num,
                'not_involved_num' => $not_involved_num,
                'not_involved_boy_num' => $not_involved_boy_num,
                'not_involved_girl_num' => $not_involved_girl_num,
                'normal_report_num' => $normal_report_num,
                'invalid_report_num' => $invalid_report_num,
                'warning_report_num' => $warning_report_num,
                'warning_report_boy_num' => $warning_report_boy_num,
                'warning_report_girl_num' => $warning_report_girl_num,
                'warning_report_level' => $warning_report_level2,
                'lowest_overall_score' => $lowest_overall_score,
                'highest_overall_score' => $highest_overall_score,
                'overall_average_score' => $overall_average_score,
                'WarningReportNum' => $WarningReportNum,
                'overall_report_score' => $overall_report_score,
                'lowest_report_score' => $lowest_report_score,
                'highest_report_score' => $highest_report_score,
                'lowest_warning_factor' => $lowest_warning_factor,
                'highest_warning_factor' => $highest_warning_factor,
                'overall_warning_factor' => $overall_warning_factor,
                'FactorInfo' => $FactorInfo,
                'user_answer_num' => $user_answer_num,
                'RatingScaleInfo' => [
                    'task_start_time' => $TaskInfo['start_time'],
                    'task_end_time' => $TaskInfo['end_time'],
                    'unit_name' => $TaskInfo['unit_name'],
                    'mode_name' => $RatingScaleInfo['mode_name'],
                    'rating_scale_name' => $RatingScaleInfo['name'],
                    'rating_scale_introduce' => $RatingScaleInfo['introduce'],
                    'rating_scale_notice' => $RatingScaleInfo['notice'],
                    'rating_scale_previous_name' => $RatingScaleInfo['previous_name'],
                    'group_rating_scale' => [
                        '中小学生心理健康诊断测验(MHT)',
                        '小学生心理健康评定量表(MHRSP)',
                        '症状自评量表(SCL-90)',
                        '中小学生心理健康诊断测验（MHT）',
                        '小学生心理健康评定量表（MHRSP）',
                        '症状自评量表（SCL-90）',
                    ]
                ]
            ]);

        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 教职工任务测评团体报告导出数据（优化版）
     * @param int $task_id
     * @param int $rating_scale_id
     * @param array $uid
     * @return bool|string
     */
    public function WorkersTaskGroupReportExportData(int $task_id, int $rating_scale_id, array $uid = []): bool|string
    {
        try {
            $where = [
                ['task_id', '=', $task_id],
                ['rating_scale_id', '=', $rating_scale_id]
            ];
            if (!empty($uid)) {
                $where[] = ['uid', 'in', $uid];
            }

            $WorkersTaskUserModel = new WorkersTaskUserModel();
            // 1. 优化查询：只取必要字段，关联查询精简
            $query = $WorkersTaskUserModel->field('id,task_id,rating_scale_id,uid,is_finish,result_id')
                ->where($where)
                ->with([
                    'WorkersUser',
                    'WorkersTaskUserResult' => function ($query) {
                        $query->with([
                            'TaskFactorScore' => function ($query) {
                                $query->field('id,factor_id,score,is_warning,warning_id')
                                    ->with([
                                        'TeamRatingScaleFactor',
                                        'RatingScaleFactorWarning'
                                    ]);
                            }
                        ]);
                    }
                ]);

            // 2. 大数据量分批处理
            $batchSize = 200;
            $target_num = 0;
            $involved_num = 0;
            $involved_boy_num = 0;
            $involved_girl_num = 0;
            $not_involved_num = 0;
            $not_involved_boy_num = 0;
            $not_involved_girl_num = 0;
            $normal_report_num = 0;
            $invalid_report_num = 0;
            $warning_report_num = 0;
            $warning_report_boy_num = 0;
            $warning_report_girl_num = 0;
            $warning_report_level = [];

            // 总分统计变量
            $totalScoreSum = 0;
            $totalScoreCount = 0;
            $lowest_overall_score = null;
            $highest_overall_score = null;

            // 因子统计变量
            $FactorInfo = [];
            $FactorWarningArray = [];
            $WarningReportNum = 0;
            $overall_report_score_sum = 0;
            $lowest_report_score = null;
            $highest_report_score = null;

            // 预警因子数量统计
            $WarningFactorStats = [
                'count' => 0,
                'sum' => 0,
                'min' => null,
                'max' => null
            ];

            $user_answer_num = 0;

            // 分批处理
            $query->cache(true,300)->chunk($batchSize, function ($chunk) use (
                &$target_num,
                &$involved_num, &$involved_boy_num, &$involved_girl_num,
                &$not_involved_num, &$not_involved_boy_num, &$not_involved_girl_num,
                &$normal_report_num, &$invalid_report_num, &$warning_report_num,
                &$warning_report_boy_num, &$warning_report_girl_num, &$warning_report_level,
                &$totalScoreSum, &$totalScoreCount, &$lowest_overall_score, &$highest_overall_score,
                &$FactorInfo, &$FactorWarningArray, &$WarningReportNum, &$overall_report_score_sum,
                &$lowest_report_score, &$highest_report_score, &$WarningFactorStats, &$user_answer_num
            ) {
                $chunkData = $chunk->toArray();
                foreach ($chunkData as $item) {
                    $target_num++;
                    // 测评次数统计
                    if ($item['answer_role'] == 1) {
                        $user_answer_num++;
                    }

                    // 总分统计
                    if (!empty($item['total_score'])) {
                        $totalScoreSum += $item['total_score'];
                        $totalScoreCount++;
                        $lowest_overall_score = is_null($lowest_overall_score)
                            ? $item['total_score']
                            : min($lowest_overall_score, $item['total_score']);
                        $highest_overall_score = is_null($highest_overall_score)
                            ? $item['total_score']
                            : max($highest_overall_score, $item['total_score']);
                    }

                    if ($item['is_finish'] == 1) {
                        $currentWarningFactorNum = 0;

                        // 报告有效性
                        if ($item['is_valid'] == 0) {
                            $invalid_report_num++;
                        } elseif ($item['is_warning'] == 1) {
                            $warning_report_num++;
                            if ($item['sex'] == 1) {
                                $warning_report_boy_num++;
                            } elseif ($item['sex'] == 2) {
                                $warning_report_girl_num++;
                            }
                        } else {
                            $normal_report_num++;
                        }

                        // 参与人统计
                        if ($item['sex'] == 1) {
                            $involved_boy_num++;
                        } elseif ($item['sex'] == 2) {
                            $involved_girl_num++;
                        }
                        $involved_num++;

                        // 因子处理（同上面方法逻辑）
                        foreach ($item['TaskFactorScore'] as $factor) {
                            $factorName = $factor['factor_name'];
                            $factorId = $factor['factor_id'];

                            if (!isset($FactorInfo[$factorName])) {
                                $FactorInfo[$factorName] = [
                                    'name' => $factorName,
                                    'min' => $factor['score'],
                                    'max' => $factor['score'],
                                    'sum' => $factor['score'],
                                    'count' => 1,
                                    'factor_explain' => $factor['factor_explain'] ?? '',
                                    'warning_arr' => [],
                                    'normal' => 1
                                ];
                            } else {
                                $FactorInfo[$factorName]['min'] = min($FactorInfo[$factorName]['min'], $factor['score']);
                                $FactorInfo[$factorName]['max'] = max($FactorInfo[$factorName]['max'], $factor['score']);
                                $FactorInfo[$factorName]['sum'] += $factor['score'];
                                $FactorInfo[$factorName]['count']++;
                                $FactorInfo[$factorName]['normal']++;
                            }

                            if ($factor['is_warning'] == 1) {
                                $currentWarningFactorNum++;
                                $WarningReportNum++;
                                $overall_report_score_sum += $factor['score'];

                                $lowest_report_score = is_null($lowest_report_score)
                                    ? $factor['score']
                                    : min($lowest_report_score, $factor['score']);
                                $highest_report_score = is_null($highest_report_score)
                                    ? $factor['score']
                                    : max($highest_report_score, $factor['score']);

                                if (!isset($FactorWarningArray[$factorId])) {
                                    $FactorWarningArray[$factorId] = [
                                        'factor_name' => $factorName,
                                        'num' => 1
                                    ];
                                } else {
                                    $FactorWarningArray[$factorId]['num']++;
                                }

                                if (!isset($FactorInfo[$factorName]['warning_arr'][$factor['warning_name']])) {
                                    $FactorInfo[$factorName]['warning_arr'][$factor['warning_name']] = 1;
                                } else {
                                    $FactorInfo[$factorName]['warning_arr'][$factor['warning_name']]++;
                                }
                                $FactorInfo[$factorName]['normal']--;

                                if (!isset($warning_report_level[$factorId])) {
                                    $warning_report_level[$factorId] = [
                                        'name' => $factorName,
                                        'num' => 1,
                                        'boy' => $item['sex'] == 1 ? 1 : 0,
                                        'girl' => $item['sex'] == 2 ? 1 : 0
                                    ];
                                } else {
                                    $warning_report_level[$factorId]['num']++;
                                    if ($item['sex'] == 1) {
                                        $warning_report_level[$factorId]['boy']++;
                                    } elseif ($item['sex'] == 2) {
                                        $warning_report_level[$factorId]['girl']++;
                                    }
                                }
                            }
                        }

                        if ($currentWarningFactorNum > 0) {
                            $WarningFactorStats['count']++;
                            $WarningFactorStats['sum'] += $currentWarningFactorNum;
                            $WarningFactorStats['min'] = is_null($WarningFactorStats['min'])
                                ? $currentWarningFactorNum
                                : min($WarningFactorStats['min'], $currentWarningFactorNum);
                            $WarningFactorStats['max'] = is_null($WarningFactorStats['max'])
                                ? $currentWarningFactorNum
                                : max($WarningFactorStats['max'], $currentWarningFactorNum);
                        }
                    } else {
                        if ($item['sex'] == 1) {
                            $not_involved_boy_num++;
                        } elseif ($item['sex'] == 2) {
                            $not_involved_girl_num++;
                        }
                        $not_involved_num++;
                    }
                }
                unset($chunkData); // 释放内存
            });

            // 计算统计值（同上面方法逻辑）
            $lowest_overall_score = $lowest_overall_score ?? 0;
            $highest_overall_score = $highest_overall_score ?? 0;
            $overall_average_score = $totalScoreCount > 0
                ? round($totalScoreSum / $totalScoreCount, 2)
                : 0;

            $overall_report_score = $WarningReportNum > 0
                ? round($overall_report_score_sum / $WarningReportNum, 2)
                : 0;
            $lowest_report_score = $lowest_report_score ?? 0;
            $highest_report_score = $highest_report_score ?? 0;

            $lowest_warning_factor = $WarningFactorStats['count'] > 0
                ? $WarningFactorStats['min']
                : 0;
            $highest_warning_factor = $WarningFactorStats['count'] > 0
                ? $WarningFactorStats['max']
                : 0;
            $overall_warning_factor = $WarningFactorStats['count'] > 0
                ? round($WarningFactorStats['sum'] / $WarningFactorStats['count'], 2)
                : 0;

            $FactorInfo = array_map(function ($item) {
                $item['average'] = round($item['sum'] / $item['count'], 2);
                $item['warning_arr'] = array_map(function ($num, $name) {
                    return ['name' => $name, 'num' => $num];
                }, $item['warning_arr'], array_keys($item['warning_arr']));
                unset($item['sum'], $item['count']);
                return $item;
            }, $FactorInfo);
            $FactorInfo = array_values($FactorInfo);

            $WarningFactorArrayList = [];
            foreach ($FactorWarningArray as $item) {
                $WarningFactorArrayList[] = $item;
            }
            array_multisort(array_column($WarningFactorArrayList, 'num'), SORT_DESC, $WarningFactorArrayList);

            $WarningFactorArrayName = implode('、', array_column($FactorWarningArray, 'factor_name'));
            $WarningFactorArrayName2 = implode('、', array_column($WarningFactorArrayList, 'factor_name'));

            $warning_report_level2 = array_values(array_map(function ($item) {
                return [
                    'name' => $item['name'],
                    'num' => $item['num'],
                    'boy' => $item['boy'] ?? 0,
                    'girl' => $item['girl'] ?? 0
                ];
            }, $warning_report_level));

            // 获取关联信息
            $RatingScaleModel = new RatingScaleModel();
            $RatingScaleInfo = $RatingScaleModel->with('RatingScaleMode')->find($rating_scale_id);
            $TaskModel = new WorkersTaskModel();
            $TaskInfo = $TaskModel->with(['user' => function ($query) {
                $query->with(['unitName']);
            }])->find($task_id);

            return success([
                // 同上面方法的返回结构
                'WarningFactorArrayName2' => $WarningFactorArrayName2,
                'WarningFactorArrayName' => $WarningFactorArrayName,
                'WarningFactorArrayList' => $WarningFactorArrayList,
                'target_num' => $target_num,
                'involved_num' => $involved_num,
                'involved_boy_num' => $involved_boy_num,
                'involved_girl_num' => $involved_girl_num,
                'not_involved_num' => $not_involved_num,
                'not_involved_boy_num' => $not_involved_boy_num,
                'not_involved_girl_num' => $not_involved_girl_num,
                'normal_report_num' => $normal_report_num,
                'invalid_report_num' => $invalid_report_num,
                'warning_report_num' => $warning_report_num,
                'warning_report_boy_num' => $warning_report_boy_num,
                'warning_report_girl_num' => $warning_report_girl_num,
                'warning_report_level' => $warning_report_level2,
                'lowest_overall_score' => $lowest_overall_score,
                'highest_overall_score' => $highest_overall_score,
                'overall_average_score' => $overall_average_score,
                'WarningReportNum' => $WarningReportNum,
                'overall_report_score' => $overall_report_score,
                'lowest_report_score' => $lowest_report_score,
                'highest_report_score' => $highest_report_score,
                'lowest_warning_factor' => $lowest_warning_factor,
                'highest_warning_factor' => $highest_warning_factor,
                'overall_warning_factor' => $overall_warning_factor,
                'FactorInfo' => $FactorInfo,
                'user_answer_num' => $user_answer_num,
                'RatingScaleInfo' => [
                    'task_start_time' => $TaskInfo['start_time'],
                    'task_end_time' => $TaskInfo['end_time'],
                    'unit_name' => $TaskInfo['unit_name'],
                    'mode_name' => $RatingScaleInfo['mode_name'],
                    'rating_scale_name' => $RatingScaleInfo['name'],
                    'rating_scale_introduce' => $RatingScaleInfo['introduce'],
                    'rating_scale_notice' => $RatingScaleInfo['notice'],
                    'rating_scale_previous_name' => $RatingScaleInfo['previous_name'],
                    'group_rating_scale' => [
                        '中小学生心理健康诊断测验(MHT)',
                        '小学生心理健康评定量表(MHRSP)',
                        '症状自评量表(SCL-90)',
                        '中小学生心理健康诊断测验（MHT）',
                        '小学生心理健康评定量表（MHRSP）',
                        '症状自评量表（SCL-90）',
                    ]
                ]
            ]);

        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 任务测评团体报告导出数据-区域（优化版）
     * @param int $task_id
     * @param array $unit_task_id
     * @param int $rating_scale_id
     * @return bool|string
     */
    public function regionTaskGroupReportExportData(int $task_id,array $unit_task_id, int $rating_scale_id): bool|string
    {
        try {
            $TaskUserModel = new TaskUserModel();
            // 1. 查询优化：只获取需要的字段，减少数据传输量
            $query = $TaskUserModel->field('id,task_id,rating_scale_id,uid,is_finish,result_id')
                ->where([
                    ['task_id', 'in', $unit_task_id],
                    ['rating_scale_id', '=', $rating_scale_id],
                ])
                ->with([
                    'user',
                    'TaskUserResult' => function ($query) {
                        $query->with([
                            'TaskFactorScore' => function ($query) {
                                // 只加载因子统计必要字段
                                $query->field('id,factor_id,score,is_warning,warning_id')
                                    ->with([
                                        'TeamRatingScaleFactor',
                                        'RatingScaleFactorWarning'
                                    ]);
                            }
                        ]);
                    }
                ]);


            // 2. 大数据量分批处理
            $batchSize = 100;
            $target_num = 0;
            $involved_num = 0;
            $involved_boy_num = 0;
            $involved_girl_num = 0;
            $not_involved_num = 0;
            $not_involved_boy_num = 0;
            $not_involved_girl_num = 0;
            $normal_report_num = 0;
            $invalid_report_num = 0;
            $warning_report_num = 0;
            $warning_report_boy_num = 0;
            $warning_report_girl_num = 0;
            $warning_report_level = [];

            // 总分统计变量
            $totalScoreSum = 0;
            $totalScoreCount = 0;
            $lowest_overall_score = null;
            $highest_overall_score = null;

            // 因子统计变量
            $FactorInfo = [];
            $FactorWarningArray = [];
            $WarningReportNum = 0;
            $overall_report_score_sum = 0;
            $lowest_report_score = null;
            $highest_report_score = null;

            // 预警因子数量统计
            $WarningFactorStats = [
                'count' => 0,
                'sum' => 0,
                'min' => null,
                'max' => null
            ];

            $user_answer_num = 0;

            // 分批处理
            $query->cache(true,300)->chunk($batchSize, function ($chunk) use (
                &$target_num,
                &$involved_num, &$involved_boy_num, &$involved_girl_num,
                &$not_involved_num, &$not_involved_boy_num, &$not_involved_girl_num,
                &$normal_report_num, &$invalid_report_num, &$warning_report_num,
                &$warning_report_boy_num, &$warning_report_girl_num, &$warning_report_level,
                &$totalScoreSum, &$totalScoreCount, &$lowest_overall_score, &$highest_overall_score,
                &$FactorInfo, &$FactorWarningArray, &$WarningReportNum, &$overall_report_score_sum,
                &$lowest_report_score, &$highest_report_score, &$WarningFactorStats, &$user_answer_num
            ) {
                $chunkData = $chunk->toArray();
                foreach ($chunkData as $item) {
                    $target_num++;
                    // 测评次数统计
                    if ($item['answer_role'] == 1) {
                        $user_answer_num++;
                    }

                    // 总分统计
                    if (!empty($item['total_score'])) {
                        $totalScoreSum += $item['total_score'];
                        $totalScoreCount++;
                        $lowest_overall_score = is_null($lowest_overall_score)
                            ? $item['total_score']
                            : min($lowest_overall_score, $item['total_score']);
                        $highest_overall_score = is_null($highest_overall_score)
                            ? $item['total_score']
                            : max($highest_overall_score, $item['total_score']);
                    }

                    if ($item['is_finish'] == 1) {
                        $currentWarningFactorNum = 0;

                        // 报告有效性
                        if ($item['is_valid'] == 0) {
                            $invalid_report_num++;
                        } elseif ($item['is_warning'] == 1) {
                            $warning_report_num++;
                            if ($item['sex'] == 1) {
                                $warning_report_boy_num++;
                            } elseif ($item['sex'] == 2) {
                                $warning_report_girl_num++;
                            }
                        } else {
                            $normal_report_num++;
                        }

                        // 参与人统计
                        if ($item['sex'] == 1) {
                            $involved_boy_num++;
                        } elseif ($item['sex'] == 2) {
                            $involved_girl_num++;
                        }
                        $involved_num++;

                        // 因子处理（同上面方法逻辑）
                        foreach ($item['TaskFactorScore'] as $factor) {
                            $factorName = $factor['factor_name'];
                            $factorId = $factor['factor_id'];

                            if (!isset($FactorInfo[$factorName])) {
                                $FactorInfo[$factorName] = [
                                    'name' => $factorName,
                                    'min' => $factor['score'],
                                    'max' => $factor['score'],
                                    'sum' => $factor['score'],
                                    'count' => 1,
                                    'factor_explain' => $factor['factor_explain'] ?? '',
                                    'warning_arr' => [],
                                    'normal' => 1
                                ];
                            } else {
                                $FactorInfo[$factorName]['min'] = min($FactorInfo[$factorName]['min'], $factor['score']);
                                $FactorInfo[$factorName]['max'] = max($FactorInfo[$factorName]['max'], $factor['score']);
                                $FactorInfo[$factorName]['sum'] += $factor['score'];
                                $FactorInfo[$factorName]['count']++;
                                $FactorInfo[$factorName]['normal']++;
                            }

                            if ($factor['is_warning'] == 1) {
                                $currentWarningFactorNum++;
                                $WarningReportNum++;
                                $overall_report_score_sum += $factor['score'];

                                $lowest_report_score = is_null($lowest_report_score)
                                    ? $factor['score']
                                    : min($lowest_report_score, $factor['score']);
                                $highest_report_score = is_null($highest_report_score)
                                    ? $factor['score']
                                    : max($highest_report_score, $factor['score']);

                                if (!isset($FactorWarningArray[$factorId])) {
                                    $FactorWarningArray[$factorId] = [
                                        'factor_name' => $factorName,
                                        'num' => 1
                                    ];
                                } else {
                                    $FactorWarningArray[$factorId]['num']++;
                                }

                                if (!isset($FactorInfo[$factorName]['warning_arr'][$factor['warning_name']])) {
                                    $FactorInfo[$factorName]['warning_arr'][$factor['warning_name']] = 1;
                                } else {
                                    $FactorInfo[$factorName]['warning_arr'][$factor['warning_name']]++;
                                }
                                $FactorInfo[$factorName]['normal']--;

                                if (!isset($warning_report_level[$factorId])) {
                                    $warning_report_level[$factorId] = [
                                        'name' => $factorName,
                                        'num' => 1,
                                        'boy' => $item['sex'] == 1 ? 1 : 0,
                                        'girl' => $item['sex'] == 2 ? 1 : 0
                                    ];
                                } else {
                                    $warning_report_level[$factorId]['num']++;
                                    if ($item['sex'] == 1) {
                                        $warning_report_level[$factorId]['boy']++;
                                    } elseif ($item['sex'] == 2) {
                                        $warning_report_level[$factorId]['girl']++;
                                    }
                                }
                            }
                        }

                        if ($currentWarningFactorNum > 0) {
                            $WarningFactorStats['count']++;
                            $WarningFactorStats['sum'] += $currentWarningFactorNum;
                            $WarningFactorStats['min'] = is_null($WarningFactorStats['min'])
                                ? $currentWarningFactorNum
                                : min($WarningFactorStats['min'], $currentWarningFactorNum);
                            $WarningFactorStats['max'] = is_null($WarningFactorStats['max'])
                                ? $currentWarningFactorNum
                                : max($WarningFactorStats['max'], $currentWarningFactorNum);
                        }
                    } else {
                        if ($item['sex'] == 1) {
                            $not_involved_boy_num++;
                        } elseif ($item['sex'] == 2) {
                            $not_involved_girl_num++;
                        }
                        $not_involved_num++;
                    }
                }
                unset($chunkData); // 释放内存
            });

            // 计算统计值（同上面方法逻辑）
            $lowest_overall_score = $lowest_overall_score ?? 0;
            $highest_overall_score = $highest_overall_score ?? 0;
            $overall_average_score = $totalScoreCount > 0
                ? round($totalScoreSum / $totalScoreCount, 2)
                : 0;

            $overall_report_score = $WarningReportNum > 0
                ? round($overall_report_score_sum / $WarningReportNum, 2)
                : 0;
            $lowest_report_score = $lowest_report_score ?? 0;
            $highest_report_score = $highest_report_score ?? 0;

            $lowest_warning_factor = $WarningFactorStats['count'] > 0
                ? $WarningFactorStats['min']
                : 0;
            $highest_warning_factor = $WarningFactorStats['count'] > 0
                ? $WarningFactorStats['max']
                : 0;
            $overall_warning_factor = $WarningFactorStats['count'] > 0
                ? round($WarningFactorStats['sum'] / $WarningFactorStats['count'], 2)
                : 0;

            $FactorInfo = array_map(function ($item) {
                $item['average'] = round($item['sum'] / $item['count'], 2);
                $item['warning_arr'] = array_map(function ($num, $name) {
                    return ['name' => $name, 'num' => $num];
                }, $item['warning_arr'], array_keys($item['warning_arr']));
                unset($item['sum'], $item['count']);
                return $item;
            }, $FactorInfo);
            $FactorInfo = array_values($FactorInfo);

            $WarningFactorArrayList = [];
            foreach ($FactorWarningArray as $item) {
                $WarningFactorArrayList[] = $item;
            }
            array_multisort(array_column($WarningFactorArrayList, 'num'), SORT_DESC, $WarningFactorArrayList);

            $WarningFactorArrayName = implode('、', array_column($FactorWarningArray, 'factor_name'));
            $WarningFactorArrayName2 = implode('、', array_column($WarningFactorArrayList, 'factor_name'));

            $warning_report_level2 = array_values(array_map(function ($item) {
                return [
                    'name' => $item['name'],
                    'num' => $item['num'],
                    'boy' => $item['boy'] ?? 0,
                    'girl' => $item['girl'] ?? 0
                ];
            }, $warning_report_level));

            // 获取关联信息
            $RatingScaleModel = new RatingScaleModel();
            $RatingScaleInfo = $RatingScaleModel->with('RatingScaleMode')->find($rating_scale_id);
            $TaskModel = new PlatformTaskModel();
            $TaskInfo = $TaskModel->with(['user' => function ($query) {
                $query->with(['unitName']);
            }])->find($task_id);

            return success([
                // 同上面方法的返回结构
                'WarningFactorArrayName2' => $WarningFactorArrayName2,
                'WarningFactorArrayName' => $WarningFactorArrayName,
                'WarningFactorArrayList' => $WarningFactorArrayList,
                'target_num' => $target_num,
                'involved_num' => $involved_num,
                'involved_boy_num' => $involved_boy_num,
                'involved_girl_num' => $involved_girl_num,
                'not_involved_num' => $not_involved_num,
                'not_involved_boy_num' => $not_involved_boy_num,
                'not_involved_girl_num' => $not_involved_girl_num,
                'normal_report_num' => $normal_report_num,
                'invalid_report_num' => $invalid_report_num,
                'warning_report_num' => $warning_report_num,
                'warning_report_boy_num' => $warning_report_boy_num,
                'warning_report_girl_num' => $warning_report_girl_num,
                'warning_report_level' => $warning_report_level2,
                'lowest_overall_score' => $lowest_overall_score,
                'highest_overall_score' => $highest_overall_score,
                'overall_average_score' => $overall_average_score,
                'WarningReportNum' => $WarningReportNum,
                'overall_report_score' => $overall_report_score,
                'lowest_report_score' => $lowest_report_score,
                'highest_report_score' => $highest_report_score,
                'lowest_warning_factor' => $lowest_warning_factor,
                'highest_warning_factor' => $highest_warning_factor,
                'overall_warning_factor' => $overall_warning_factor,
                'FactorInfo' => $FactorInfo,
                'user_answer_num' => $user_answer_num,
                'RatingScaleInfo' => [
                    'task_start_time' => $TaskInfo['start_time'],
                    'task_end_time' => $TaskInfo['end_time'],
                    'unit_name' => $TaskInfo['unit_name'],
                    'mode_name' => $RatingScaleInfo['mode_name'],
                    'rating_scale_name' => $RatingScaleInfo['name'],
                    'rating_scale_introduce' => $RatingScaleInfo['introduce'],
                    'rating_scale_notice' => $RatingScaleInfo['notice'],
                    'rating_scale_previous_name' => $RatingScaleInfo['previous_name'],
                    'group_rating_scale' => [
                        '中小学生心理健康诊断测验(MHT)',
                        '小学生心理健康评定量表(MHRSP)',
                        '症状自评量表(SCL-90)',
                        '中小学生心理健康诊断测验（MHT）',
                        '小学生心理健康评定量表（MHRSP）',
                        '症状自评量表（SCL-90）',
                    ]
                ]
            ]);

        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }
}